package com.bjpowernode.boss.common.error;

import com.bjpowernode.boss.common.enums.AjaxCode;
import com.bjpowernode.boss.web.models.result.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler({BossException.class})
    public AjaxResult handlerBossException(BossException e){
        AjaxCode ajaxCode = e.getAjaxCode();
        log.error("Boss异常->{}->{}",ajaxCode.getCode(),ajaxCode.getMsg());
        return new AjaxResult(e.getAjaxCode(),"");
    }
    //处理Bean Validation异常
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public AjaxResult handlerMethodArgumentNotValidException(MethodArgumentNotValidException e){
        //获取异常的信息， 在属性上， 因为哪个约束失败了, 提示信息
        BindingResult br = e.getBindingResult();
        Map<String,String> map = new HashMap<>();
        //发送验证失败的属性集合，集合成员FieldError(属性,message的值)
        List<FieldError> fieldErrors = br.getFieldErrors();
        fieldErrors.forEach(fieldError -> {
            String field =  fieldError.getField();//验证失败的属性名称
            String message =  fieldError.getDefaultMessage();//注解中的message属性值
            if(!map.containsKey(field)){
                map.put(field,message);
            }else{
                map.put(field,map.get(field)+";"+message);
            }
        });
        return new AjaxResult(AjaxCode.REQUEST_PARAM_ERROR,map);
    }
}
